package org.springblade.modules.admin.controller.es;

import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.springblade.core.tool.api.R;
import org.springblade.modules.admin.entity.MaintainParts;
import org.springblade.modules.admin.entity.es.PartsDocument;
import org.springblade.modules.admin.mapper.es.PartsDocumentMapper;
import org.springblade.modules.admin.service.MaintainPartsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * l
 * 演示springboot项目实际使用
 * <p>
 * Copyright © 2021 xpc1024 All Rights Reserved
 **/
@RestController
@RequestMapping("/es-search")
public class EsSearchController {

	@Resource
	private PartsDocumentMapper documentMapper;
	@Autowired
	private MaintainPartsService partsService;

	/**
	 * 创建索引
	 *
	 * @return
	 */
	@GetMapping("/createIndex")
	public Boolean createIndex() {
		//创建索引
		return documentMapper.createIndex();
	}

	/**
	 * 插入数据
	 *
	 * @return
	 */
	@GetMapping("insert")
	public Integer insert() {

		List<MaintainParts> list = partsService.list();

		List<PartsDocument> partsDocuments = new ArrayList<>();
		for (MaintainParts maintainPart : list) {
			PartsDocument document = new PartsDocument();
			document.setId(maintainPart.getId());
			document.setName(maintainPart.getName());
			document.setNameSynonyms(maintainPart.getName());
			document.setNamePinyin(maintainPart.getName());
			document.setAncestors(maintainPart.getAncestors());

			partsDocuments.add(document);
		}
		return documentMapper.insertBatch(partsDocuments);
	}


	@PutMapping("update")
	public R<Boolean> update(@PathVariable Long id, @RequestBody PartsDocument document) {
		document.setId(id);
		document.setNameSynonyms(document.getName());
		document.setNamePinyin(document.getName());
		return R.status(documentMapper.updateById(document) > 0 ? true : false);

	}


	/**
	 * PUT /test_parts_document
	 * {
	 *    "settings": {
	 *         "analysis": {
	 *             "analyzer": {
	 *                 "custom_pinyin": {
	 *                     "type": "custom",
	 *                     "tokenizer": "ik_max_word",
	 *                     "filter": ["my_pinyin", "word_delimiter"]
	 *                 },
	 *                 "custom_synonyms": {
	 *                     "type": "custom",
	 *                     "tokenizer": "ik_smart",
	 *                     "filter": ["my_synonym", "word_delimiter"]
	 *                 }
	 *             },
	 *             "filter": {
	 *                 "my_pinyin": {
	 *                     "type" : "pinyin",
	 *                     "keep_full_pinyin": false,
	 *                     "keep_joined_full_pinyin": true,
	 *                     "keep_original": false,
	 *                     "limit_first_letter_length": 16,
	 *                     "remove_duplicated_term": true,
	 *                     "none_chinese_pinyin_tokenize": false
	 *                 },
	 *                 "my_synonym": {
	 *                     "type": "synonym",
	 *                     "updateable": true,
	 *                     "synonyms_path": "analysis/synonyms.txt"
	 *                 }
	 *             }
	 *         }
	 *   }
	 * }
	 */

	/**
	 * POST /test_parts_document/_mapping
	 *   {
	 *           "properties": {
	 *               "name": {
	 *                   "type": "text",
	 *                   "analyzer": "ik_max_word",
	 *                   "search_analyzer": "ik_smart"
	 *               },
	 *               "ancestors": {
	 *                   "type": "keyword"
	 *               },
	 *               "namePinyin":{
	 *                   "type": "text",
	 *                   "analyzer": "custom_pinyin",
	 *                   "search_analyzer": "ik_smart"
	 *               },
	 *               "nameSynonyms": {
	 *                   "type": "text",
	 *                   "analyzer": "ik_smart",
	 *                   "search_analyzer": "custom_synonyms"
	 *               }
	 *           }
	 *   }
	 */

	/**
	 * 根据名称查询(包含)
	 *
	 * @param title
	 * @return
	 */
	@GetMapping("/listByTitle")
	public List<PartsDocument> listDocumentByTitle(@RequestParam String title) {

		LambdaEsQueryWrapper<PartsDocument> wrapper = new LambdaEsQueryWrapper<>();
		//目前采用自定义分词器的方式,先用ik分词器分词,然后是用pinyin分词器对ik分词后的结果单独进行分词,目前这种效果最佳
		wrapper.matchPhrase(PartsDocument::getName, title)
			.or()
			.matchPhrase(PartsDocument::getNameSynonyms, title)
			.or()
			.matchPhrase(PartsDocument::getNamePinyin, title);


//		wrapper.multiMatchQuery(title, Operator.OR, 10.0F, "name.ik")
//			.or()
//			.multiMatchQuery(title, Operator.OR, 5.0F, "name.pinyin");
		//============================
//		wrapper.matchPhrase("name.ik", title, 10.0F)
//			.or()
//			.matchPhrase("name.pinyin", title, 5.0F);
//		String queryStr = QueryUtils.combine(Link.OR,
//			QueryUtils.buildQueryString(PartsDocument::getName, title, Query.EQ, Link.OR),
//			QueryUtils.buildQueryString(PartsDocument::getName, title, Query.MATCH))
//			+ QueryUtils.buildQueryString(PartsDocument::getName, "*" + title + "*", Query.EQ);
//		wrapper.queryStringQuery(queryStr);
//		wrapper.match("name.pinyin", title);
		wrapper.notSelect(PartsDocument::getNameSynonyms,PartsDocument::getNamePinyin);
		List<PartsDocument> partsDocuments = documentMapper.selectList(wrapper);

//		List<MaintainParts> maintainParts = BeanUtil.copyToList(partsDocuments, MaintainParts.class);
		return partsDocuments;
	}


	/**
	 * 使用原生RestHighLevelClient进行查询
	 *
	 * @param title
	 */
//	@GetMapping("/listByTitle1")
//	public void test(@RequestParam String title) {
//		// RestHighLevelClient进行查询
//		String indexName = "test_parts_document";
//		SearchRequest searchRequest = new SearchRequest(indexName);
//		BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//		TermQueryBuilder titleTerm = QueryBuilders.termQuery("title", title);
//		TermsQueryBuilder creatorTerm = QueryBuilders.termsQuery("creator", title);
//		boolQueryBuilder.should(titleTerm);
//		boolQueryBuilder.must(creatorTerm);
//		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//		searchSourceBuilder.query(boolQueryBuilder);
//		searchRequest.source(searchSourceBuilder);
//		try {
//			SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//			// 然后从searchResponse中通过各种方式解析出DocumentList 省略代码...
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}
}
